﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TaskLib;

namespace TaskView
{
    public partial class ViewForm : Form
    {
        private ITaskFactory factory = null;

        public ViewForm()
        {
            factory = new SimpleTaskFactory();            
            
            InitializeComponent();

            factory.TasksChanged += new TasksChangedEventHandler(factory_TasksChanged);            
        }

        protected override void  OnFormClosing(FormClosingEventArgs e)
        {
            Cursor prev = Cursor;
            Cursor = Cursors.WaitCursor;
            factory.SerializeTasks(".\\tasks.xml");
            Cursor = prev;

            base.OnFormClosing(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            Cursor prev = Cursor;
            Cursor = Cursors.WaitCursor;
            factory.DeserializeTasks(".\\tasks.xml");
            Cursor = prev;

            base.OnLoad(e);
        }

        #region Control event handlers

        void factory_TasksChanged(TasksChangedEventArgs e)
        {
            UpdateTaskLists(e);
        }
      
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditTask(null);
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            EditTask(null);
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var menuItem = sender as ToolStripMenuItem;
            if (menuItem != null)
            {
                ListView list = GetListViewFromToolStripMenuItem(menuItem);
                EditSelectedTasks(list);
            }
        }

        private void markCompletedNowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var menuItem = sender as ToolStripMenuItem;
            if (menuItem != null)
            {
                ListView list = GetListViewFromToolStripMenuItem(menuItem);
                if (list != null)
                {
                    EditSelectedTasks(list, true);
                }
            }
        }        

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            UpdateTaskLists(new TasksChangedEventArgs(factory, factory.Tasks, null));
        }

        private void editButton_Click(object sender, EventArgs e)
        {

        }

        #endregion

        #region Task utilities

        private long EditTask(Task task = null)
        {
            var taskEditForm = new TaskEditForm(task == null? TaskEditForm.EditMode.NewlyCreated : TaskEditForm.EditMode.EditExisting, task);
            DialogResult result = taskEditForm.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                if (task == null)
                {
                    task = factory.CreateTask("", DateTime.MinValue, "", false);                
                }

                factory.UpdateTaskDescription(task.ID, taskEditForm.Description);
                factory.UpdateTaskScheduled(task.ID, taskEditForm.Scheduled);
                factory.UpdateTaskCompletion(task.ID, taskEditForm.Completion);
                factory.UpdateTaskCompleted(task.ID, taskEditForm.Completed);
                factory.UpdateTaskComment(task.ID, taskEditForm.Comment);   

                return task.ID;
            }
            return Task.InvalidId;
        }      
        #endregion

        #region Event notification helpers        

        private void UpdateTaskLists(TasksChangedEventArgs e)
        {
            upcomingListView.Items.Clear();
            historyListView.Items.Clear();

            foreach (Task task in e.tasks)
            {
                if (task.Scheduled > DateTime.Now)
                {
                    var item = new ListViewItem(new string[] {  task.Description, 
                                                                task.Scheduled.ToString(TaskListView.DateColumnFormat),                                                     
                                                                task.Comment });
                    item.Tag = task;
                    upcomingListView.Items.Add(item);
                }
                else
                {
                    var item = new ListViewItem(new string[] { task.Description, 
                                                               task.Scheduled.ToString(TaskListView.DateColumnFormat),
                                                               task.Completed? task.Completion.ToString(TaskListView.DateColumnFormat) : "", 
                                                               task.Comment });
                    if (! task.Completed)
                    {
                        item.ForeColor = Color.Red;
                    }

                    item.Tag = task;
                    historyListView.Items.Add(item);
                }
            }

            upcomingListView.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.HeaderSize);
            upcomingListView.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            
            historyListView.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.HeaderSize);
            historyListView.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.HeaderSize);
            historyListView.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
        }

        private ListView GetListViewFromToolStripMenuItem(ToolStripMenuItem menuItem)
        {
            ListView list = null;
            if (menuItem != null)
            {
                var toolStrip = menuItem.Owner;
                if (toolStrip != null)
                {
                    var menuStrip = toolStrip as ContextMenuStrip;
                    if (menuStrip != null)
                    {
                        list = menuStrip.SourceControl as ListView;
                        return list;
                    }
                }
            }
            return list;
        }        

        private void EditSelectedTasks(ListView list, bool markCompleted = false)
        {
            if (list != null)
            {
                foreach (ListViewItem item in list.SelectedItems)
                {
                    Task task = item.Tag as Task;
                    if (task != null)
                    {
                        if (markCompleted)
                        {
                            task.Completion = DateTime.Now;
                            task.Completed = true;
                        }
                        
                        EditTask(task);
                    }
                }
            } 
        }

        #endregion        
    }
}
